package Hot100.twoSearch;

public class searchRange {
    public static void main(String[] args) {
        int[] nums = {1,1,2};
        int target = 1;
        int[] ans = new searchRange().searchRange(nums,target);
        for (int i = 0; i < ans.length; i++) {
            System.out.println(ans[i]);
        }
    }
    public int[] searchRange(int[] nums, int target) {
        int low = 0,high = nums.length - 1;
        int[] ans = {-1,-1};
        if(high == -1){
            return ans;
        }
        int mid = 0;
        while (low <= high){
            mid = (high - low) / 2 + low;
            if(nums[mid] ==target){
                int first = mid;
                int last = mid;
                ans[0] = first;
                ans[1] = first;
                //向左找到第一个等于target的数
                while (--first >= 0){
                    if(nums[first] == target){
                        ans[0] = first;
                    }else
                        break;
                }
                //向右找到最后一个等于target的数
                while (++last < nums.length ){
                    if (nums[last] == target){
                        ans[1] = last;
                    }else{
                        break;
                    }
                }
                break;
            } else if (nums[mid] > target) {
                high = mid - 1;
            }else {
                low = mid + 1;
            }
        }
        return ans;
    }
}
